package com.shanghaionstar.discover.charge.presenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.Constants;

import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.ChargingProfileEntity;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.result.PollingResult;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.DiscoverActivity;
import com.shanghaionstar.carmanage.CarManageActivity;
import com.shanghaionstar.discover.charge.ChargeModeNotificationFragment;
import com.shanghaionstar.discover.charge.ChargeModeTimeFragment;
import com.shanghaionstar.discover.charge.iview.IChargeModeView;
import com.shanghaionstar.discover.charge.model.ChargeModeItem;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.remote.model.RemoteModel;
import com.shanghaionstar.remote.service.RemoteService;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 7828wc on 16/7/21.
 */
public class ChargeModePresenter extends BasePresenter<Class<?>> {
    IChargeModeView view;
    private List<ChargeModeItem> list;
    private BaseActivity mContext;
    private ChargingProfileEntity chargingProfileEntity;
//    private RemoteCommandUtil remoteCommandUtil;
    private RemoteService remoteCommandUtil;
    FunctionNameFindId[] chargeIds = { FunctionNameFindId.Charge_realtime, FunctionNameFindId.Charge_Delay,
            FunctionNameFindId.Charge_IntelligentChage };
    private Subscription pollingSubscription;

    public ChargeModePresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
        registerPollingSub();
    }

    @Override
    public void setView(IMVPView<Class<?>> view) {
        super.setView(view);
        this.view = (IChargeModeView) view;
        mContext = (BaseActivity) view.onActivity();
    }

    public void initList(){
        list = new ArrayList<>(3);
        list.add(new ChargeModeItem(mContext.getString(R.string.charge_mode_instant_title),mContext.getString(R.string.charge_mode_instant),R.drawable.icon_instant_charge));
        list.add(new ChargeModeItem(mContext.getString(R.string.charge_mode_delay_title),mContext.getString(R.string.charge_mode_delay),R.drawable.icon_delay_charge));
        list.add(new ChargeModeItem(mContext.getString(R.string.charge_mode_smart_title),mContext.getString(R.string.charge_mode_smart),R.drawable.icon_smart_charge));
        view.initView(list);
        remoteCommandUtil = new RemoteService(mContext);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.SERVICE_RESPONSE_FAILURE:
                case Constants.SERVICE_RESPONSE_ERROR:
                    ErrorInfo errorInfo = (ErrorInfo) msg.getData().getSerializable("errorInfo");
                    String errorMsg = ErrorCodeUtil.getErrorMsgByCode(mContext, errorInfo);
                    AlertDialogUtil.showAlertDialog(mContext, mContext.getString(R.string.dialog_warning), errorMsg);
                    view.setLoading(false);
                    break;
                case Constants.SERVICE_HTTP_ERROR:
                    HttpException e = (HttpException) msg.getData().getSerializable("HttpException");
                    AlertDialogUtil.showDialogByExceptionCode(mContext, e);
                    view.setLoading(false);
                    break;
                case Constants.SERVICE_RESPONSE_INPROGRESS:
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 处理Polling 返回结果
     */
    private void registerPollingSub() {
        pollingSubscription = RxBus.getDefault()
                .toObserverable(RxConstants.ALL_PAGE_ALERT, PollingResult.class)
                .filter(new Func1<PollingResult, Boolean>() {
                    @Override
                    public Boolean call(PollingResult pollingResult) {
                        return pollingResult.getRequestType().equalsIgnoreCase(RemoteCommandsType.COMMAND_SETCHARGINGPROFILE.value())
                                || pollingResult.getRequestType().equalsIgnoreCase(RemoteCommandsType.COMMAND_GETCHARGINGPROFILE.value());
                    }
                })
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<PollingResult>() {
                    @Override
                    public void call(PollingResult pollingResult) {
//                        if (RequestStatus.Success.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
                            updateView(pollingResult);
//                        }
                    }
                });
    }

    public void requestChargeMode(){
        RemoteModel remoteModel = new RemoteModel.Builder().setRemoteCommandsType(RemoteCommandsType.COMMAND_GETCHARGINGPROFILE).create();
        requestChargeMode(remoteModel);
    }


    public void requestChargeMode(RemoteModel remoteModel){
        view.setLoading(true);
        subscription = remoteCommandUtil.commandByType(remoteModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if(view != null && throwable != null)
                            view.onResponseError((OnStarException) throwable);
                    }
                });
   }

    public void updateView(PollingResult result) {
        view.setLoading(false);
        if (result.getRequestStatus().equals(RequestStatus.Success.getStringValue())) {
            if (RemoteCommandsType.COMMAND_GETCHARGINGPROFILE.value().equals(result.getRequestType())) {
                BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.Charge_Get.getStringValue(), ReportReqParam.getChargeModeInfoReqParm(true));
                try {
                    String json = result.getJson();
                    JSONObject jsonObject = new JSONObject(json);
                    String keyStr = jsonObject.getJSONObject("commandResponse").getJSONObject("body")
                            .getString("chargingProfile");
                    chargingProfileEntity = GsonHelper.fromJson(keyStr,ChargingProfileEntity.class);
                    Log.e("zk", "entity=" + chargingProfileEntity);
                    ChargingProfileEntity.ChargeMode chargeMode = chargingProfileEntity.getChargeModeEnum();
                    for (ChargeModeItem item : list) {
                        item.selected = false;
                    }
                    switch (chargeMode) {
                        case IMMEDIATE:
                            list.get(0).selected = true;
                            break;
                        case DEPARTURE_BASED:
                            list.get(1).selected = true;
                            break;
                        case RATE_BASED:
                            list.get(2).selected = true;
                            break;
                    }
                    view.notifyChange();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(mContext, "analyze json failure", Toast.LENGTH_SHORT).show();
                }
            } else if (RemoteCommandsType.COMMAND_SETCHARGINGPROFILE.value().equals(result.getRequestType())) {
                BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.Charge_Save.getStringValue(), ReportReqParam.getSetChargeModeReqParm(true));
                ToastView toast = new ToastView(mContext);
                toast.showToast(mContext.getString(R.string.departure_time_upadte_success));
            }
        } else if (result.getRequestStatus().equals(RequestStatus.Failure.getStringValue())) {
            if (RemoteCommandsType.COMMAND_GETCHARGINGPROFILE.value().equals(result.getRequestType())) {
                String msg = result.getErrorInfo()==null?"":result.getErrorInfo().getMsg();
                BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.Charge_Get.getStringValue(), ReportReqParam.getChargeModeInfoReqParm(false,msg));
                Message message = Message.obtain();
                Bundle data = new Bundle();
                data.putSerializable("errorInfo", result.getErrorInfo());
                message.setData(data);
                message.what = Constants.SERVICE_RESPONSE_ERROR;
                handler.sendMessage(message);
            } else if (RemoteCommandsType.COMMAND_SETCHARGINGPROFILE.value().equals(result.getRequestType())) {
                String msg = result.getErrorInfo()==null?"":result.getErrorInfo().getMsg();
                BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.Charge_Save.getStringValue(), ReportReqParam.getSetChargeModeReqParm(false,msg));
                Message message = Message.obtain();
                Bundle data = new Bundle();
                data.putSerializable("errorInfo", result.getErrorInfo());
                message.setData(data);
                message.what = Constants.SERVICE_RESPONSE_ERROR;
                handler.sendMessage(message);
//				ToastView toast = new ToastView(getActivity());
//				toast.showToast(getString(R.string.departure_time_upadte_failed));
            }
        }
    }

    public void onItemClick(int position){
        BusinessUtil.sendReportByClickType(mContext,
                chargeIds[position].getStringValue());
        for (int i = 0; i < list.size(); i++) {
            ChargeModeItem item = list.get(i);
            item.selected = i == position;
        }
    }

    public void onRightClick(){
        mContext.changeFragment(mContext.getSupportFragmentManager(),
                new ChargeModeNotificationFragment(), ChargeModeNotificationFragment.class, true);
    }
    public void switchToChargeTime(){
        if(mContext instanceof DiscoverActivity) {
            BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Charge_DepartTime.getStringValue());
            mContext.changeFragment(mContext.getSupportFragmentManager(), new ChargeModeTimeFragment(),
                    ChargeModeTimeFragment.class, true);
        }else if(mContext instanceof CarManageActivity){
            Intent it = new Intent(mContext,DiscoverActivity.class);
            it.putExtra(FinalConstants.JUMP_FLAG,ChargeModeTimeFragment.class.getName());
            mContext.startActivity(it);
        }
    }

    public void save(){
        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Charge_Save.getStringValue());
        if (chargingProfileEntity == null) {
            Toast.makeText(mContext, "chargeMode is null", Toast.LENGTH_SHORT).show();
            return;
        }
        view.setLoading(true);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).selected) {
                chargingProfileEntity.setChargeMode(ChargingProfileEntity.ChargeMode.values()[i + 1].name());
                break;
            }
        }
        Gson gson = new Gson();
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("chargingProfile", gson.toJsonTree(chargingProfileEntity));
        // gson.toJson(jsonObject)
        RemoteModel model = new RemoteModel.Builder()
                .setRemoteCommandsType(RemoteCommandsType.COMMAND_SETCHARGINGPROFILE)
                .setBody(gson.toJson(jsonObject))
                .create();
        requestChargeMode(model);
    }

    @Override
    public void finish() {
        super.finish();
        if (pollingSubscription != null && !pollingSubscription.isUnsubscribed()) {
            pollingSubscription.unsubscribe();
            pollingSubscription = null;
        }
    }
}
